/**
 * 
 */
package hu.gbalage.owl.editor.items.classes;

import java.util.Set;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.semanticweb.owl.inference.OWLReasoner;
import org.semanticweb.owl.inference.OWLReasonerException;
import org.semanticweb.owl.model.OWLClass;
import hu.gbalage.owl.editor.IOWLEditorItem;
import hu.gbalage.owl.editor.OWLEditorManager;
import hu.gbalage.owl.editor.TabManager;

/**
 * @author balage
 *
 */
public class ClassHierarchyItemWithReasoner implements IOWLEditorItem {

	Tree tree;
	
	/* (non-Javadoc)
	 * @see hu.gbalage.owl.editor.IOWLEditorItem#getColor()
	 */
	public RGB getColor() {
		return new RGB(50,150,255);
	}

	/* (non-Javadoc)
	 * @see hu.gbalage.owl.editor.IOWLEditorItem#getTitle()
	 */
	public String getTitle() {
		return "Inferred Class Hierarchy";
	}

	private OWLClass nothing;
	
	/* (non-Javadoc)
	 * @see hu.gbalage.owl.editor.IOWLEditorItem#init(org.eclipse.swt.widgets.Composite, hu.gbalage.owl.editor.OWLEditorManager)
	 */
	public void init(Composite parent, OWLEditorManager manager,final TabManager tabManager) {
		parent.setLayout(new FillLayout());
		
		tree = new Tree(parent,SWT.NONE);
		
		//OWLOntology o = manager.getOntology();
		
		OWLClass thing = manager.getThing();
		TreeItem thingitem = new TreeItem(tree,SWT.NONE);
		thingitem.setText("Thing");
		thingitem.setData(thing);
	
		nothing = manager.getNothing();
		
		createSubClassItems(thingitem, manager.getReasoner());
		
		tree.addSelectionListener(new SelectionAdapter(){
			@Override
			public void widgetSelected(SelectionEvent e) {
				TreeItem[] items = tree.getSelection();
				if (items.length != 1) return;
				tabManager.selectEntity((OWLClass)items[0].getData());
			}
		});
		
		/*Set<OWLClass> clazz = o.getReferencedClasses();
		for(OWLClass cl : clazz){
			TreeItem item = new TreeItem(tree,SWT.NONE);
			item.setText(cl.getURI().toString());
		}*/
		parent.layout();
	}

	private void createSubClassItems(TreeItem parent, OWLReasoner o){
		OWLClass clazz = (OWLClass)parent.getData();
		System.out.println("subclasses for "+clazz.getURI());
		
		try {
			for(Set<OWLClass> as : o.getSubClasses(clazz)) 
				for(OWLClass c : as) if(!c.equals(nothing)){
					TreeItem item = new TreeItem(parent,SWT.NONE);
					item.setText(c.getURI().getFragment());
					item.setData(c);
					
					createSubClassItems(item, o);
			}
		} catch (OWLReasonerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
